package com.wirelesshomecontrol;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.vaadin.Application;
import com.vaadin.service.ApplicationContext;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.*;
import com.wirelesshomecontrol.db.jdbcconnect;
import com.wirelesshomecontrol.gui.WirelessHomeControlWindow;
import com.wirelesshomecontrol.gui.windows.LoginWindow;

public class WirelesshomecontrolApplication extends Application implements ApplicationContext.TransactionListener {

	private static ThreadLocal<WirelesshomecontrolApplication> currentApplication = new ThreadLocal<WirelesshomecontrolApplication>();

	private String currentUser = null;
	private jdbcconnect cn = new jdbcconnect();
	
	public void init() {
		getContext().addTransactionListener(this);
		setMainWindow(new LoginWindow());
	}

	public void transactionStart (Application app, Object o) {
		if (app == WirelesshomecontrolApplication.this){
			currentApplication.set(this);
		}
	}

	public void transactionEnd (Application app, Object o) {
		if(app == WirelesshomecontrolApplication.this) {
			currentApplication.set(null);
			currentApplication.remove();
		}
	}
	
	public static WirelesshomecontrolApplication getInstance() {
		return currentApplication.get();
	}
	
	public void authenticate(String login, String password) throws Exception {
		String loginName ="'" + login + "'";
		String loginPass = "'" + password + "'";
		String query = "Select username, password from user_login where username= " + loginName + " and password=" + loginPass;
		try {
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection (cn.dbUrl,"root","Hippos44");
			PreparedStatement stmt = con.prepareStatement(query);
			stmt.execute();
			 ResultSet rs = stmt.getResultSet ();
			   int count = 0;
			   while (rs.next ())
			   {
			       ++count;
			   }
			   
			if (count<1) {
				cn.Update_Log_DB("login", 0, new java.sql.Timestamp(new java.util.Date().getTime()), login +" Login Failed!");
				throw new Exception ("Login Failed!");
				
			}
			 currentUser = login;
			 loadProtectedResources();
			if (con !=null){
			con.close();
			}
			} //end try

			catch(ClassNotFoundException e) {
			e.printStackTrace();
			}

			catch(SQLException e) {
			e.printStackTrace();
			}
			}
	
	public String getCurrentUser() {
		return currentUser;
	}
	
	private void loadProtectedResources() throws Exception {
		setMainWindow(new WirelessHomeControlWindow());
		cn.Update_Log_DB("login", 0, new java.sql.Timestamp(new java.util.Date().getTime()), getCurrentUser() + " Login Successful!");
	}
	
}